package controllers

import (
	"strings"

	"newAi/new_web/models"
	"newAi/new_web/static/nway_fs_gateway"
	"fmt"

	"github.com/astaxie/beego"
)

type GateWayController struct {
	BaseController
}

func (self *GateWayController) List() {
	group_id, _ := self.GetInt64("group_id")
	self.Data["group_id"] = group_id
	self.Data["pageTitle"] = "网关管理"
	self.Data["auth"] = false
	if self.userId == 1 {
		self.Data["auth"] = true
	}

	self.display()
}

func (self *GateWayController) Add() {
	group_id, _ := self.GetInt64("group_id")
	self.Data["group_id"] = group_id
	gateway_group, err := models.GatewayGroupIdName()
	self.CheckError(err)
	for _, v := range gateway_group {
		if group_id == v.Id {
			self.Data["group_name"] = v.Group_name
		}
	}
	self.Data["pageTitle"] = "新增网关"
	self.display()
}

func (self *GateWayController) Edit() {
	self.Data["pageTitle"] = "编辑网关"
	group_id, _ := self.GetInt64("group_id")
	self.Data["group_id"] = group_id
	gateway_group, err := models.GatewayGroupIdName()
	self.CheckError(err)
	for _, v := range gateway_group {
		if group_id == v.Id {
			self.Data["group_name"] = v.Group_name
		}
	}
	id, _ := self.GetInt("id", 0)
	GateWay, _ := models.GateWayGetById(id)
	callGateway, err := models.CheckCallGateway(GateWay.Call_gateway_id)

	var fsGateway opfsgw.Fs_Gateway
	fsextpath, err := models.GetFSExternalPath("FS_External_path")
	if err != nil {
		beego.Error("Not config FS_External_path")
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	fsGateway.SetXmlPath(fsextpath)
	gateway := fsGateway.GetAGateway(GateWay.Gateway_name)

	row := make(map[string]interface{})
	row["id"] = GateWay.Id
	row["gateway_name"] = GateWay.Gateway_name
	row["gateway_group"] = GateWay.Gateway_group_id
	row["gateway_state"] = GateWay.Gateway_state
	row["gateway_url"] = GateWay.Gateway_url
	row["gateway_auth"] = GateWay.Gateway_auth
	row["max_concurrent"] = GateWay.Max_concurrent
	row["gateway_type"] = callGateway.Gateway_type
	row["register_number"] = callGateway.Register_number

	row["realm"] = gateway.GetRealm()
	row["password"] = gateway.GetPassword()
	row["proxy"] = gateway.GetProxy()
	row["register"] = gateway.GetRegister()
	row["username"] = gateway.GetUsername()
	self.Data["gateway"] = row
	self.display()

}

func (self *GateWayController) AjaxSave() {
	GateWay_id, _ := self.GetInt("id")
	var fsGateway opfsgw.Fs_Gateway
	inputs := self.Input()
	if GateWay_id == 0 {
		// 检查登录名是否已经存在
		GateWay := new(models.GateWay)
		_, err := models.GateWayGetByName(GateWay.Gateway_name)
		if err == nil {
			self.ajaxMsg("名称已经存在", MSG_ERR)
		}
		a, _ := self.GetInt("gateway_type")
		if a != 2 {
			//写入文件
			fsGateway.SetGatewayName(inputs.Get("gateway_name"))
			fsGateway.SetPassword(inputs.Get("password"))
			fsGateway.SetProxy(inputs.Get("proxy"))
			fsGateway.SetRealm(inputs.Get("realm"))
			fsGateway.SetFromUser(inputs.Get("fromuser"))
			if a == 0 {
				fsGateway.SetRegister("false")
			} else {
				fsGateway.SetRegister("true")

			}
			fsGateway.SetUsername(inputs.Get("username"))
			path, err := models.GetFSExternalPath("FS_External_path")
			if err != nil {
				fmt.Println("err:", err)
				self.ajaxMsg(err.Error(), MSG_ERR)
			}
			fsGateway.SetXmlPath(path)

			if len(fsGateway.GetGatewayName()) > 1 {
				if len(fsGateway.GetRealm()) > 1 {
					err := fsGateway.SaveFile()
					if err != nil {
						fmt.Println("err:", err)
						beego.Error("Write to xml error:", err)
						self.ajaxMsg(err.Error(), MSG_ERR)
					}

				}
			}
		}
		callgateway := models.CallGateWay{}
		callgateway.Gateway_name = strings.TrimSpace(self.GetString("gateway_name"))
		callgateway.Gateway_url = strings.TrimSpace(self.GetString("gateway_name"))
		callgateway.Call_prefix = " "
		callgateway.Max_call, _ = self.GetInt("max_concurrent")
		callgateway.Added_autodial = false
		callgateway.Effective_caller_id_number = " "
		//var gatewaytype, _ = self.GetInt("gateway_type")
		callgateway.Gateway_type = a + 1
		callgateway.Register_number = self.GetString("register_number")
		if callgateway.Register_number == "" {
			callgateway.Register_number = " "
		}
		//新增
		gid, err := models.CallGateWayAdd(callgateway)
		if err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}

		GateWay.Gateway_name = strings.TrimSpace(self.GetString("gateway_name"))
		GateWay.Gateway_group_id, _ = self.GetInt64("group_id")
		GateWay.Gateway_state, _ = self.GetInt("gateway_state")
		GateWay.Max_concurrent, _ = self.GetInt("max_concurrent")
		GateWay.Call_gateway_id = gid
		//新增
		if _, err := models.GateWayAdd(GateWay); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)
	} else {

		fsextpath, err := models.GetFSExternalPath("FS_External_path")
		if err != nil {
			beego.Error("Not config FS_External_path")
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		fsGateway.SetXmlPath(fsextpath)
		//判断修改的网关名字是否与之前的一样
		GateWay, _ := models.GateWayGetById(GateWay_id)
		if inputs.Get("gateway_name") != GateWay.Gateway_name {
			err := fsGateway.EarseGateway(GateWay.Gateway_name)
			if err != nil {
				self.ajaxMsg(err.Error(), MSG_ERR)
			}
		}
		//写入文件
		a, _ := self.GetInt("gateway_type")
		if a != 2 {

			fsGateway.SetGatewayName(inputs.Get("gateway_name"))
			fsGateway.SetPassword(inputs.Get("password"))
			fsGateway.SetProxy(inputs.Get("proxy"))
			fsGateway.SetRealm(inputs.Get("realm"))
			fsGateway.SetFromUser(inputs.Get("fromuser"))
			if a == 0 {
				fsGateway.SetRegister("false")
			} else {
				fsGateway.SetRegister("true")

			}
			//fsGateway.SetRegister(inputs.Get("register"))
			fsGateway.SetUsername(inputs.Get("username"))
			if len(fsGateway.GetGatewayName()) > 1 {
				if len(fsGateway.GetRealm()) > 1 {
					err = fsGateway.SaveFile()
					if err != nil {
						beego.Error("Write to xml error:", err)
						self.ajaxMsg(err.Error(), MSG_ERR)
					}
				}
			}
		}
		callgateway := models.CallGateWay{}
		callgateway.Id = GateWay.Call_gateway_id
		callgateway.Gateway_name = strings.TrimSpace(self.GetString("gateway_name"))
		callgateway.Gateway_url = strings.TrimSpace(self.GetString("gateway_name"))
		callgateway.Call_prefix = " "
		callgateway.Max_call, _ = self.GetInt("max_concurrent")
		callgateway.Added_autodial = false
		callgateway.Effective_caller_id_number = " "

		callgateway.Gateway_type = a + 1
		callgateway.Register_number = self.GetString("register_number")
		if callgateway.Register_number == "" {
			callgateway.Register_number = " "
		}
		//修改
		if err := models.CallGateWayEdit(callgateway); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}

		//修改
		GateWay.Gateway_name = strings.TrimSpace(self.GetString("gateway_name"))
		GateWay.Gateway_group_id, _ = self.GetInt64("group_id")
		GateWay.Gateway_state, _ = self.GetInt("gateway_state")
		GateWay.Max_concurrent, _ = self.GetInt("max_concurrent")

		if err := GateWay.Update(); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)

	}

}

func (self *GateWayController) AjaxDel() {

	GateWay_id, _ := self.GetInt("id")
	GateWay, _ := models.GateWayGetById(GateWay_id)

	fsextpath, err := models.GetFSExternalPath("FS_External_path")
	if err != nil {
		beego.Error("Not config FS_External_path")
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	var fsGateway opfsgw.Fs_Gateway
	fsGateway.SetXmlPath(fsextpath)
	//判断修改的网关名字是否与之前的一样
	err = fsGateway.EarseGateway(GateWay.Gateway_name)
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	if err := models.CallDelete(GateWay.Call_gateway_id); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	if err := GateWay.Delete(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}

func (self *GateWayController) Table() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	self.pageSize = limit
	//网关组名称
	group_id, _ := self.GetInt64("group_id")
	gateway_group, err := models.GatewayGroupIdName()
	self.CheckError(err)

	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "gateway_group_id", group_id)
	result, count := models.GateWayGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["gateway_name"] = v.Gateway_name
		for _, b := range gateway_group {
			if v.Gateway_group_id == b.Id {
				row["gateway_group"] = b.Group_name
			}
		}
		if v.Gateway_state == 0 {
			row["gateway_state"] = "正常"
		} else {
			row["gateway_state"] = "锁定"
		}
		//row["gateway_state"] =v.Gateway_state
		row["max_concurrent"] = v.Max_concurrent
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}
